/* Copyright 2013-2015 www.snakerflow.com.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.snaker.engine.access.jdbc;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snaker.engine.DBAccess;
import org.snaker.engine.access.AbstractDBAccess;
import org.snaker.engine.access.DBAccessSql;
import org.snaker.engine.access.dialect.PostgresqlDialect;
import org.snaker.engine.entity.Process;
import cn.hutool.db.Db;

/**
 * JDBC方式的数据库访问 在无事务控制的情况下，使用cglib的拦截器+ThreadLocale控制
 * 
 * @see org.snaker.engine.access.transaction.DataSourceTransactionInterceptor
 * @author yuqs
 * @since 1.0
 */
public class JdbcAccess extends AbstractDBAccess implements DBAccess {
    private static final Logger log = LoggerFactory.getLogger(JdbcAccess.class);

    public void initialize(final Object accessObject) {
        if (accessObject == null) {
            return;
        }
        if (accessObject instanceof DataSource) {
            this.dataSource = (DataSource) accessObject;
        }
    }

    /**
     * 返回数据库连接对象
     * 
     * @return
     * @throws java.sql.SQLException
     */
    protected Connection getConnection() throws SQLException {
        return Db.use(dataSource).getConnection();
    }

    /**
     * 是否orm框架，否
     */
    public boolean isORM() {
        return false;
    }

    /**
     * 使用原生JDBC操作BLOB字段
     */
    public void saveProcess(final Process process) {
        super.saveProcess(process);
        if (process.getBytes() != null) {
            try {
                if (getDialect(dataSource) instanceof PostgresqlDialect) {
                    Db.use(dataSource).execute(DBAccessSql.PROCESS_UPDATE_BLOB, new String(process.getBytes()), process.getId());
                } else {
                    Db.use(dataSource).execute(DBAccessSql.PROCESS_UPDATE_BLOB, process.getBytes(), process.getId());
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
    }

    /**
     * 使用原生JDBC操作BLOB字段
     */
    public void updateProcess(final Process process) {
        if (process.getBytes() != null) {
            try {
                if (getDialect(dataSource) instanceof PostgresqlDialect) {
                    Db.use(dataSource).execute(DBAccessSql.PROCESS_UPDATE_BLOB, new String(process.getBytes()), process.getId());
                } else {
                    Db.use(dataSource).execute(DBAccessSql.PROCESS_UPDATE_BLOB, process.getBytes(), process.getId());
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
    }

    /**
     * 根据流程定义名称获得流程定义版本
     */
    public Integer getLatestProcessVersion(final String name) {
        Integer resutl = 0;
        try {
            Number num = Db.use(dataSource).queryNumber(DBAccessSql.QUERY_VERSION + " where name = ?", name);
            if (num != null) {
                resutl = num.intValue();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resutl;
    }

    /**
     * 保存或修改
     */
    public void saveOrUpdate(final Map<String, Object> map) {
        String sql = (String) map.get(DBAccessSql.KEY_SQL);
        Object[] args = (Object[]) map.get(DBAccessSql.KEY_ARGS);
        if (log.isDebugEnabled()) {
            log.debug("增删改数据(需手动提交事务)=\n" + sql);
        }
        try {
            Db.use(dataSource).execute(sql, args);
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
    }

    /**
     * 查询对象
     */
    public <T> T queryObject(final Class<T> clazz, final String sql, final Object... args) {
        T result = null;
        List<T> list = queryList(clazz, sql, args);
        if (list != null && list.size() > 0) {
            result = list.get(0);
        }
        return result;
    }

    /**
     * 查询List
     */
    public <T> List<T> queryList(final Class<T> clazz, final String sql, final Object... args) {
        List<T> result = null;
        try {
            result = Db.use(dataSource).query(sql, clazz, args);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * count
     */
    public long queryCount(final String sql, final Object... args) {
        long result = 0;
        try {
            result = Db.use(dataSource).count(sql, args);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }
}
